//
//  GLSegmentedControl.m
//  pick
//
//  Created by 史宵宵 on 2017/11/30.
//  Copyright © 2017年 GL. All rights reserved.
//

#import "GLSegmentedControl.h"
@interface GLSegmentedControl()
@property(nonatomic,strong)NSArray *titleArray;
@property(weak,nonatomic)UIView *BgView;
@property(weak,nonatomic)UIButton *selectButton;
@end

@implementation GLSegmentedControl

- (instancetype)initWithFrame:(CGRect)frame andTitleArray:(NSArray *)titleArray{
    if (self=[super initWithFrame:frame]) {
        self.titleArray=titleArray;
        [self creatUI];
    }
    return self;
}
- (void)creatUI{
    self.layer.cornerRadius=CGRectGetHeight(self.bounds)/2.0;
    self.backgroundColor=[UIColor whiteColor];
    CGFloat width=CGRectGetWidth(self.bounds)/2;
    CGFloat height=CGRectGetHeight(self.bounds);
    UIView *bgview=[[UIView alloc]initWithFrame:CGRectMake(2, 1, width - 2, height - 2)];
    bgview.backgroundColor=KBACKNAVIGATIONCOLOR;
    bgview.layer.cornerRadius=height/2.0 - 2;
    [self addSubview:bgview];
    self.BgView=bgview;
    for (int i=0; i<self.titleArray.count; i++) {
        UIButton *button=[[UIButton alloc]initWithFrame:CGRectMake(i*width, 0, width, height)];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setBackgroundColor:[UIColor clearColor]];
        [button setTitle:self.titleArray[i] forState:UIControlStateNormal];
        [button setTitle:self.titleArray[i] forState:UIControlStateSelected];
        button.tag=i;
        [button addTarget:self action:@selector(clickbutton:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:button];
        if (!i) {
            button.selected=YES;
            self.selectButton=button;
        }
    }
    
}
- (void)clickbutton:(UIButton *)sender{
    if (self.selectindex) {
        self.selectindex(sender.tag);
    }
    [UIView animateWithDuration:1.0 animations:^{
        if(sender.tag){
            self.BgView.transform=CGAffineTransformMakeTranslation(sender.tag*CGRectGetWidth(self.BgView.bounds), 0);
        }
        else
        {
            self.BgView.transform=CGAffineTransformIdentity;
        }
    }completion:^(BOOL finished) {
        self.selectButton.selected=NO;
        sender.selected=YES;
        self.selectButton=sender;
    }];
}

@end
